package com.gzhryc.shared_device.oem.h5.mng.controllers.place;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceBusinessConfig;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceProfitUser;
import com.gzhryc.shared_device.oem.code.place.dao.models.IncomeRatioContent;
import com.gzhryc.shared_device.oem.code.place.services.PlaceBusinessConfigService;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.PlaceProfitUserService;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import com.gzhryc.shared_device.oem.h5.mng.dto.place.PlaceUser;
import com.gzhryc.shared_device.oem.h5.mng.dto.place.PlaceUserIncomeRatio;
import com.gzhryc.system.SysConstants;
import com.gzhryc.system.dao.db.Manager;

public class PlaceUserController {

    @Route(value = "/place/user/list.data")
    public ListResult<PlaceUser> listData(HttpServletRequest request) {
        ListResult<PlaceUser> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long placeId = WebUtils.getLong(request, "placeId");
        if (placeId != null) {
            PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(placeId);
            User user = UserService.self().getById(physicalStore.getUserId());

            List<PlaceProfitUser> placeProfitUserList = PlaceProfitUserService.self().findJoinByPlaceId(placeId);

            Map<String, Double> incomeRatioData = new HashMap<>();
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(new ArrayList<>());

            PlaceUser placeUser = new PlaceUser();
            placeUser.setUserId(user.getId());
            placeUser.setUserName(user.getName());
            placeUser.setUserPhone(user.getPhone());
            placeUser.setRoleType(ERoleType.Agent.index());
            placeUser.setRoleTypeName(ERoleType.Agent.note());
            placeUser.setCanUpdate(false);
            placeUser.setIncomeRatioItems(new ArrayList<>());
            result.getBody().getData().add(placeUser);

            if (placeProfitUserList != null && placeProfitUserList.size() > 0) {
                for (PlaceProfitUser profitUser : placeProfitUserList) {
                    PlaceUser userItem = new PlaceUser();
                    userItem.setUserId(profitUser.getUserId());
                    userItem.setUserName(profitUser.getUser().getName());
                    userItem.setUserPhone(profitUser.getUser().getPhone());
                    userItem.setRoleType(profitUser.getRoleType());
                    userItem.setRoleTypeName(profitUser.getRoleTypeName());
                    userItem.setNote(profitUser.getNote());

                    if (StringTools.isNotBlank(profitUser.getIncomeRatioContent())) {
                        userItem.setIncomeRatioItems(new ArrayList<>());
                        IncomeRatioContent incomeRatioContent = JsonTools.fromJson(profitUser.getIncomeRatioContent(), IncomeRatioContent.class);
                        for (IncomeRatioContent.Item item : incomeRatioContent.getItems()) {
                            PlaceUser.IncomeRatioItem incomeRatioItem = new PlaceUser.IncomeRatioItem();
                            incomeRatioItem.setBusinessType(item.getBusinessType());
                            incomeRatioItem.setBusinessTypeName(EBusinessType.note(item.getBusinessType()));
                            incomeRatioItem.setIncomeRatio(item.getIncomeRatio());
                            userItem.getIncomeRatioItems().add(incomeRatioItem);

                            Double incomeRatio = incomeRatioData.get(item.getBusinessType());
                            if (incomeRatio == null) {
                                incomeRatio = 0.0;
                            }
                            incomeRatio = incomeRatio + item.getIncomeRatio();
                            incomeRatioData.put(item.getBusinessType(), incomeRatio);
                        }
                    }
                    result.getBody().getData().add(userItem);
                }
            }

            if (incomeRatioData.size() > 0) {
                if (placeUser.getIncomeRatioItems() == null) {
                    placeUser.setIncomeRatioItems(new ArrayList<>());
                }

                //未部署设备但给商户或员工设置了分成
                for (String businessType : incomeRatioData.keySet()) {
                    boolean flag = true;
                    for (PlaceUser.IncomeRatioItem item : placeUser.getIncomeRatioItems()) {
                        if (businessType.equals(item.getBusinessType())) {
                            flag = false;
                            break;
                        }
                    }

                    if (flag) {
                        PlaceUser.IncomeRatioItem incomeRatioItem = new PlaceUser.IncomeRatioItem();
                        incomeRatioItem.setBusinessType(businessType);
                        incomeRatioItem.setBusinessTypeName(EBusinessType.note(businessType));
                        incomeRatioItem.setIncomeRatio(100D);

                        Double incomeRatio = incomeRatioData.get(businessType);
                        if (incomeRatio != null) {
                            Double temp = 100.0 - incomeRatio;
                            if (temp > 0) {
                                incomeRatioItem.setIncomeRatio(temp);
                            } else {
                                incomeRatioItem.setIncomeRatio(0D);
                            }
                        }
                        placeUser.getIncomeRatioItems().add(incomeRatioItem);
                    }
                }
            }
        }
        return result;
    }

    @Route(value = {"/place/user/add.html"})
    public String add(HttpServletRequest request) {
    	Long placeId = WebUtils.getLong(request,"placeId");
        String businessType = WebUtils.getString(request,"businessType");
        if(StringTools.isNotBlank(businessType)){
            request.setAttribute("businessType",EBusinessType.note(businessType));
        }else {
        	List<PlaceBusinessConfig> businessConfigList = PlaceBusinessConfigService.self().findByPlaceId(placeId);
            if(businessConfigList != null && businessConfigList.size() > 0){
            	List<EBusinessType> businessTypeList = new ArrayList<EBusinessType>();
            	for(PlaceBusinessConfig busiConfig : businessConfigList) {
            		businessTypeList.add(EBusinessType.getByIndex(busiConfig.getBusinessType()));
            	}
            	request.setAttribute("businessTypeList", businessTypeList);
            }
        }
        List<ERoleType> roleTypeList = new ArrayList<>();
        roleTypeList.add(ERoleType.Partner);
        roleTypeList.add(ERoleType.Merchant);
        request.setAttribute("roleTypeList", roleTypeList);
        return "/place/user/edit.html";
    }

    @Route(value = {"/place/user/add.do"})
    public AjaxResult doAdd(HttpServletRequest request,HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增失败，请稍后再试");
        PlaceProfitUser placeProfitUser = WebUtils.getParameter(request,PlaceProfitUser.class);
        String businessType = WebUtils.getString(request,"businessType");
        Double incomeRatio = WebUtils.getDouble(request,"incomeRatio");
        User user = WebUtils.getParameter(request,"user",User.class);
        if(placeProfitUser != null && user != null && StringTools.isNotBlank(user.getPhone())) {
            if (incomeRatio == null || incomeRatio < 0 || incomeRatio > 100) {
                result.setMsg("请填写正确的分成比例");
                return result;
            }

            PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(placeProfitUser.getPlaceId());
            if(physicalStore == null){
                result.setMsg("网点不存在");
                return result;
            }

            User temp = UserService.self().getByPhone(user.getPhone());
            if (temp != null) {
                PlaceProfitUser profitUserTemp = PlaceProfitUserService.self().getByKeys(placeProfitUser.getPlaceId(), temp.getId());
                if (profitUserTemp != null) {
                    IncomeRatioContent incomeRatioContent = null;
                    if(StringTools.isNotBlank(profitUserTemp.getIncomeRatioContent())) {
                        incomeRatioContent = JsonTools.fromJson(profitUserTemp.getIncomeRatioContent(), IncomeRatioContent.class);
                    }

                    if(incomeRatioContent == null){
                        incomeRatioContent = new IncomeRatioContent();
                        IncomeRatioContent.Item item = new IncomeRatioContent.Item();
                        item.setBusinessType(businessType);
                        item.setIncomeRatio(incomeRatio);
                        incomeRatioContent.getItems().add(item);
                    }else{
                        for(IncomeRatioContent.Item item : incomeRatioContent.getItems()){
                            if(item.getBusinessType().equals(businessType)){
                                item.setIncomeRatio(incomeRatio);
                            }
                        }
                    }

                    try {
                        if (PlaceProfitUserService.self().updateNotNull(placeProfitUser, incomeRatioContent)) {
                            result.setCode(DtoConstants.SUCCESS, null);
                        }
                    } catch (LogicException e) {
                        result.setMsg(e.getMessage());
                    }

                    return result;
                }

                if(physicalStore.getUserId().equals(temp.getId())){
                    result.setMsg("用户已存在该网点中");
                    return result;
                }
            }

            IncomeRatioContent incomeRatioContent = new IncomeRatioContent();
            IncomeRatioContent.Item item = new IncomeRatioContent.Item();
            item.setBusinessType(businessType);
            item.setIncomeRatio(incomeRatio);
            incomeRatioContent.getItems().add(item);
            
            Manager manager = WebUtils.getAttribute(session, SysConstants.SESSION_LOGIN_MANAGER, Manager.class);
            
            OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE,WebConstants.PROGRAM_TYPE_NAME);
            operateInfo.setOperator(EOperatorType.Manager.index(),manager.getFullName());

            try {
                if (PlaceProfitUserService.self().add(physicalStore,placeProfitUser, user, incomeRatioContent,operateInfo)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value = {"/place/user/info.html"})
    public String info(HttpServletRequest request) {
        Long placeId = WebUtils.getLong(request,"placeId");
        Long userId = WebUtils.getLong(request,"userId");
        PlaceProfitUser profitUser = PlaceProfitUserService.self().getJoinByKeys(placeId,userId);
        WebUtils.setAttribute(request,profitUser);
        return "/place/user/info.html";
    }

    @Route(value = {"/place/user/del.do"})
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除失败，请稍后再试");
        Long placeId = WebUtils.getLong(request,"placeId");
        Long userId = WebUtils.getLong(request,"userId");
        if(placeId != null && userId != null) {
            try {
                if (PlaceProfitUserService.self().deleteByKeys(placeId,userId)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value = "/place/user/business_type/list.data")
    public ListResult<PlaceUserIncomeRatio> deviceFuncListData(HttpServletRequest request) {
        ListResult<PlaceUserIncomeRatio> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long placeId = WebUtils.getLong(request, "placeId");
        Long userId = WebUtils.getLong(request,"userId");
        if (placeId != null && userId != null) {
            PlaceProfitUser placeProfitUser = PlaceProfitUserService.self().getByKeys(placeId,userId);
            if(placeProfitUser != null && StringTools.isNotBlank(placeProfitUser.getIncomeRatioContent())){
                IncomeRatioContent incomeRatioContent = JsonTools.fromJson(placeProfitUser.getIncomeRatioContent(),IncomeRatioContent.class);
                if(incomeRatioContent.getItems() != null && incomeRatioContent.getItems().size() > 0) {
	                result.setCode(DtoConstants.SUCCESS,null);
	                result.getBody().setData(new ArrayList<>());
	                for(IncomeRatioContent.Item incomeRatioItem : incomeRatioContent.getItems()){
	                    PlaceUserIncomeRatio item = new PlaceUserIncomeRatio();
	                    item.setBusinessType(incomeRatioItem.getBusinessType());
	                    item.setBusinessTypeName(EBusinessType.note(incomeRatioItem.getBusinessType()));
	                    item.setIncomeRatio(incomeRatioItem.getIncomeRatio());
	                    result.getBody().getData().add(item);
	                }
                }
            }
        }
        return result;
    }

    @Route(value = {"/place/user/business_type/add.html"})
    public String deviceFuncAdd(HttpServletRequest request, HttpServletResponse response) {
        Long placeId = WebUtils.getLong(request, "placeId");
        Long userId = WebUtils.getLong(request,"userId");
        List<String> temp = new ArrayList<>();
        if (placeId != null && userId != null) {
            PlaceProfitUser placeProfitUser = PlaceProfitUserService.self().getByKeys(placeId,userId);
            if(placeProfitUser != null && StringTools.isNotBlank(placeProfitUser.getIncomeRatioContent())){
                IncomeRatioContent incomeRatioContent = JsonTools.fromJson(placeProfitUser.getIncomeRatioContent(),IncomeRatioContent.class);
                if(incomeRatioContent.getItems() != null && incomeRatioContent.getItems().size() > 0){
                    for(IncomeRatioContent.Item item : incomeRatioContent.getItems()){
                        temp.add(item.getBusinessType());
                    }
                }
            }
        }

        List<PlaceBusinessConfig> businessConfigList = PlaceBusinessConfigService.self().findByPlaceId(placeId);
        if(businessConfigList != null && businessConfigList.size() > 0){
        	List<EBusinessType> businessTypeList = new ArrayList<EBusinessType>();
        	for(PlaceBusinessConfig busiConfig : businessConfigList) {
        		businessTypeList.add(EBusinessType.getByIndex(busiConfig.getBusinessType()));
        	}
        	request.setAttribute("businessTypeList", businessTypeList);
        }
        return "/place/user/business_type/edit.html";
    }

    @Route(value = {"/place/user/business_type/add.do"})
    public AjaxResult doDeviceFuncAdd(HttpServletRequest request,HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增失败，请稍后再试");
        PlaceProfitUser placeProfitUser = WebUtils.getParameter(request,PlaceProfitUser.class);
        String businessType = WebUtils.getString(request,"businessType");
        Double incomeRatio = WebUtils.getDouble(request,"incomeRatio");
        if(placeProfitUser != null && StringTools.isNotBlank(businessType) && placeProfitUser.getPlaceId() != null && placeProfitUser.getUserId() != null){
            if(incomeRatio == null || incomeRatio < 0 || incomeRatio > 100){
                result.setMsg("请填写正确的分成比例");
                return result;
            }

            PlaceProfitUser profitUserTemp = PlaceProfitUserService.self().getByKeys(placeProfitUser.getPlaceId(), placeProfitUser.getUserId());
            if(profitUserTemp != null) {
                IncomeRatioContent incomeRatioContent = null;
                if (StringTools.isNotBlank(profitUserTemp.getIncomeRatioContent())) {
                    incomeRatioContent = JsonTools.fromJson(profitUserTemp.getIncomeRatioContent(), IncomeRatioContent.class);
                }

                if (incomeRatioContent == null) {
                    incomeRatioContent = new IncomeRatioContent();
                    IncomeRatioContent.Item item = new IncomeRatioContent.Item();
                    item.setBusinessType(businessType);
                    item.setIncomeRatio(incomeRatio);
                    incomeRatioContent.getItems().add(item);
                } else {
                    boolean flag = true;
                    for (IncomeRatioContent.Item item : incomeRatioContent.getItems()) {
                        if (item.getBusinessType().equals(businessType)) {
                            result.setMsg("该业务分成已添加，请点击修改");
                            return result;
                        }
                    }

                    if(flag){
                        IncomeRatioContent.Item item = new IncomeRatioContent.Item();
                        item.setBusinessType(businessType);
                        item.setIncomeRatio(incomeRatio);
                        incomeRatioContent.getItems().add(item);
                    }
                }

                try {
                    if (PlaceProfitUserService.self().updateNotNull(placeProfitUser, incomeRatioContent)) {
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                } catch (LogicException e) {
                    result.setMsg(e.getMessage());
                }
            }else {
                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(placeProfitUser.getPlaceId());
                if(physicalStore == null){
                    result.setMsg("未找到网点信息");
                    return result;
                }

                User user  = UserService.self().getById(placeProfitUser.getUserId());
                if(user == null){
                    result.setMsg("未找到用户信息");
                    return result;
                }
                IncomeRatioContent incomeRatioContent = new IncomeRatioContent();
                IncomeRatioContent.Item item = new IncomeRatioContent.Item();
                item.setBusinessType(businessType);
                item.setIncomeRatio(incomeRatio);
                incomeRatioContent.getItems().add(item);

                Manager manager = WebUtils.getAttribute(session, SysConstants.SESSION_LOGIN_MANAGER, Manager.class);
                
                OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE,WebConstants.PROGRAM_TYPE_NAME);
                operateInfo.setOperator(EOperatorType.Manager.index(),manager.getFullName());
                
                try {
                    if (PlaceProfitUserService.self().add(physicalStore,placeProfitUser,user, incomeRatioContent,operateInfo)) {
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                } catch (LogicException e) {
                    result.setMsg(e.getMessage());
                }
            }
        }
        return result;
    }

    @Route(value = {"/place/user/business_type/update.html"})
    public String deviceFuncUpdate(HttpServletRequest request, HttpServletResponse response) {
        Long placeId = WebUtils.getLong(request,"placeId");
        Long userId = WebUtils.getLong(request,"userId");
        String businessType = WebUtils.getString(request,"businessType");
        if(placeId != null && StringTools.isNotBlank(businessType) && userId != null) {
            PlaceProfitUser placeProfitUser = PlaceProfitUserService.self().getByKeys(placeId,userId);
            if(placeProfitUser != null) {
                WebUtils.setAttribute(request, placeProfitUser);

                if(StringTools.isNotBlank(placeProfitUser.getIncomeRatioContent())){
                    IncomeRatioContent incomeRatioContent = JsonTools.fromJson(placeProfitUser.getIncomeRatioContent(),IncomeRatioContent.class);
                    for(IncomeRatioContent.Item item : incomeRatioContent.getItems()){
                        if(item.getBusinessType().equals(businessType)){
                            request.setAttribute("incomeRatio",item.getIncomeRatio());
                        }
                    }
                }
            }
        }
        request.setAttribute("businessTypeName",EBusinessType.note(businessType));
        return "/place/user/business_type/edit.html";
    }

    @Route(value = {"/place/user/business_type/update.do"})
    public AjaxResult doDeviceFuncUpdate(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改失败，请稍后再试");
        PlaceProfitUser placeProfitUser = WebUtils.getParameter(request,PlaceProfitUser.class);
        String businessType = WebUtils.getString(request,"businessType");
        Double incomeRatio = WebUtils.getDouble(request,"incomeRatio");
        if(placeProfitUser != null && StringTools.isNotBlank(businessType) && placeProfitUser.getPlaceId() != null && placeProfitUser.getUserId() != null){
            if(incomeRatio == null || incomeRatio < 0 || incomeRatio > 100){
                result.setMsg("请填写正确的分成比例");
                return result;
            }

            PlaceProfitUser profitUserTemp = PlaceProfitUserService.self().getByKeys(placeProfitUser.getPlaceId(), placeProfitUser.getUserId());
            IncomeRatioContent incomeRatioContent = null;
            if(StringTools.isNotBlank(profitUserTemp.getIncomeRatioContent())) {
                incomeRatioContent = JsonTools.fromJson(profitUserTemp.getIncomeRatioContent(), IncomeRatioContent.class);
            }

            if(incomeRatioContent == null){
                result.setMsg("未找到对应的分成");
                return result;
            }else{
                boolean flag = true;
                for (IncomeRatioContent.Item item : incomeRatioContent.getItems()) {
                    if (item.getBusinessType().equals(businessType)) {
                        item.setIncomeRatio(incomeRatio);
                        flag = false;
                        break;
                    }
                }

                if(flag){
                    result.setMsg("未找到对应的分成");
                    return result;
                }
            }

            try {
                if(PlaceProfitUserService.self().updateNotNull(placeProfitUser,incomeRatioContent)){
                    result.setCode(DtoConstants.SUCCESS,null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value = {"/place/user/business_type/del.do"})
    public AjaxResult doDeviceFuncDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除失败，请稍后再试");
        Long placeId = WebUtils.getLong(request,"placeId");
        String businessType = WebUtils.getString(request,"businessType");
        Long userId = WebUtils.getLong(request,"userId");
        if(placeId != null && StringTools.isNotBlank(businessType) && userId != null) {
            try {
                if (PlaceProfitUserService.self().deleteBusinessTypeIncomeRatio(placeId,userId,businessType)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }
}
